<template>
  <div class="invoice-edit-container">
    <el-page-header :title="isEdit ? '编辑发票' : '新增发票'" @back="goBack"/>

    <div class="form-container">
      <el-form ref="invoiceFormRef" v-loading="loading" :model="invoiceForm" :rules="rules" class="invoice-form"
               label-width="120px">
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="发票号码" prop="invoiceNumber">
              <el-input v-model="invoiceForm.invoiceNumber" placeholder="请输入发票号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票类别" prop="category">
              <el-select v-model="invoiceForm.category" placeholder="请选择发票类别" style="width: 100%">
                <el-option label="增值税专用发票" value="增值税专用发票"/>
                <el-option label="增值税普通发票" value="增值税普通发票"/>
                <el-option label="增值税电子发票" value="增值税电子发票"/>
                <el-option label="收据" value="收据"/>
                <el-option label="其他" value="其他"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开票日期" prop="issueDate">
              <el-date-picker v-model="invoiceForm.issueDate" format="YYYY-MM-DD" placeholder="选择开票日期"
                              style="width: 100%"
                              type="date" value-format="YYYY-MM-DD"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 添加开票人字段 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="开票人" prop="issuer">
              <el-input v-model="invoiceForm.issuer" placeholder="请输入开票人姓名"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 购买方信息 -->
        <el-divider content-position="left">购买方信息</el-divider>
        <el-form-item label="购买方信息" prop="purchaserInfo">
          <el-input v-model="invoiceForm.purchaserInfo" :rows="3"
                    placeholder="请输入购买方信息（名称、税号、地址、电话、开户行、账号等）"
                    type="textarea">
          </el-input>
        </el-form-item>

        <!-- 销售方信息 -->
        <el-divider content-position="left">供应商信息</el-divider>
        <el-form-item label="供应商信息" prop="sellerInfo">
          <el-input v-model="invoiceForm.sellerInfo" :rows="3"
                    placeholder="供应商信息（名称、税号、地址、电话、开户行、账号等）"
                    type="textarea">
          </el-input>
        </el-form-item>

        <!-- 发票明细 -->
        <el-divider content-position="left">
          发票明细
          <el-button link style="margin-left: 10px" type="primary" @click="addDetail">
            <el-icon>
              <CirclePlus/>
            </el-icon>
            添加明细
          </el-button>
        </el-divider>

        <el-table :data="invoiceForm.details || []" border class="detail-table" style="width: 100%">
          <el-table-column label="序号" type="index" width="60"/>
          <el-table-column label="项目名称" prop="itemName">
            <template #default="scope">
              <el-input v-model="scope.row.itemName" placeholder="项目名称"/>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" prop="specificationModel" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.specificationModel" placeholder="规格型号"/>
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.unit" placeholder="单位"/>
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="quantity" width="150">
            <template #default="scope">
              <el-input-number v-model="scope.row.quantity" :min="0" :precision="2"
                               style="width: 100%" @change="calculateItemAmount(scope.$index)"/>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="unitPrice" width="150">
            <template #default="scope">
              <el-input-number v-model="scope.row.unitPrice" :min="0" :precision="2"
                               style="width: 100%" @change="calculateItemAmount(scope.$index)"/>
            </template>
          </el-table-column>
          <el-table-column label="税率%" prop="taxRate" width="100">
            <template #default="scope">
              <el-select v-model="scope.row.taxRate" @change="calculateItemAmount(scope.$index)">
                <el-option :value="0" label="0%"/>
                <el-option :value="1" label="1%"/>
                <el-option :value="3" label="3%"/>
                <el-option :value="6" label="6%"/>
                <el-option :value="9" label="9%"/>
                <el-option :value="13" label="13%"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.amount" disabled style="width: 100%"/>
            </template>
          </el-table-column>
          <el-table-column label="税额" prop="taxAmount" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.taxAmount" disabled style="width: 100%"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button circle icon="Delete" plain type="danger" @click="removeDetail(scope.$index)"/>
            </template>
          </el-table-column>
        </el-table>

        <div class="amount-summary">
          <div class="amount-item">
            <span class="amount-label">合计金额：</span>
            <span class="amount-value">¥{{ formatAmount(totalAmount) }}</span>
          </div>
          <div class="amount-item">
            <span class="amount-label">合计税额：</span>
            <span class="amount-value">¥{{ formatAmount(totalTax) }}</span>
          </div>
          <div class="amount-item">
            <span class="amount-label">价税合计：</span>
            <span class="amount-value total-price">¥{{ formatAmount(totalAmountWithTax) }}</span>
          </div>
        </div>

        <!-- 备注信息 -->
        <el-divider content-position="left">备注</el-divider>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="invoiceForm.remarks" :rows="3" placeholder="请输入备注信息" type="textarea"/>
        </el-form-item>

        <!-- 上传文件 -->
        <el-divider content-position="left">发票文件</el-divider>
        <el-form-item label="上传文件">
          <div class="upload-container">
            <!-- 使用条件渲染，图片类型使用图片卡片模式，非图片类型使用普通模式 -->
            <template v-if="fileList.length === 0 || isImageFile">
              <!-- 图片上传组件 -->
              <el-upload
                  :auto-upload="false"
                  :before-remove="beforeRemove"
                  :before-upload="handleBeforeUpload"
                  :file-list="fileList"
                  :http-request="customUploadRequest"
                  :limit="1"
                  :on-change="handleFileChange"
                  :on-error="handleUploadError"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  class="upload-demo"
                  list-type="picture-card">
                <el-icon v-if="!uploadLoading">
                  <Plus/>
                </el-icon>
                <el-icon v-else class="is-loading">
                  <Loading/>
                </el-icon>
                <template #tip>
                  <div class="el-upload__tip">
                    支持jpg, png, pdf格式文件，单个文件不超过10MB
                  </div>
                </template>
              </el-upload>
            </template>

            <template v-else>
              <!-- 非图片文件上传组件 -->
              <el-upload
                  :auto-upload="false"
                  :before-remove="beforeRemove"
                  :before-upload="handleBeforeUpload"
                  :file-list="fileList"
                  :http-request="customUploadRequest"
                  :limit="1"
                  :on-change="handleFileChange"
                  :on-error="handleUploadError"
                  :on-remove="handleRemove"
                  class="upload-demo">
                <el-button :loading="uploadLoading" type="primary">
                  {{ uploadLoading ? '上传中...' : '点击上传' }}
                </el-button>

                <!-- 下载查看按钮，仅当有非图片文件时显示 -->
                <el-button
                    v-if="fileList.length > 0 && !isImageFile"
                    style="margin-left: 10px;"
                    type="success"
                    @click="downloadFile(fileList[0])">
                  下载查看
                </el-button>

                <template #tip>
                  <div class="el-upload__tip">
                    支持jpg, png, pdf格式文件，单个文件不超过10MB
                  </div>
                </template>
              </el-upload>
            </template>

            <!-- 上传进度条 -->
            <el-progress
                v-if="uploadProgress > 0 && uploadProgress < 100"
                :percentage="uploadProgress"
                :status="uploadStatus">
            </el-progress>
          </div>

          <!-- 图片预览对话框 -->
          <el-dialog v-model="previewVisible" title="图片预览">
            <div class="preview-container">
              <img :src="previewUrl" alt="预览图片" class="preview-image"/>
            </div>
          </el-dialog>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {computed, onBeforeUnmount, onMounted, reactive, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus';
import {CirclePlus, Loading, Plus} from '@element-plus/icons-vue';
import {createInvoice, getInvoiceById, updateInvoice, uploadInvoiceFile} from '@/api/invoice.ts';
import {getFileUrl} from '@/api/file.ts';
import {Invoice, InvoiceDetail} from '@/api/types.ts';
import {UploadError, UploadFile} from '@/api/upload-types.ts';

// 格式化日期的辅助函数
const formatDate = (date: Date): string => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 定义临时文件存储
const tempFile = ref<File | null>(null);
const tempFileUrl = ref<string | null>(null);

// 在组件卸载前清理临时资源
onBeforeUnmount(() => {
  cleanupTempResources();
});

// 清理临时资源函数
const cleanupTempResources = () => {
  if (tempFileUrl.value) {
    URL.revokeObjectURL(tempFileUrl.value);
    tempFileUrl.value = null;
  }
  tempFile.value = null;
};

const router = useRouter();
const route = useRoute();
const invoiceFormRef = ref();

// 判断是否为编辑模式
const isEdit = computed(() => {
  return route.path.includes('invoice-edit');
});

// 创建空的明细项
function createEmptyDetail() {
  return {
    itemName: '',
    specificationModel: '',
    unit: '',
    quantity: 0,
    unitPrice: 0,
    taxRate: 0,
    amount: 0,
    taxAmount: 0
  };
}

// 发票表单数据
const invoiceForm = reactive<any>({
  invoiceNumber: '', // 发票编号
  category: '', // 发票类别
  issueDate: formatDate(new Date()), // 开票日期
  status: '新建', // 发票状态
  totalAmount: 0, // 总金额
  totalTax: 0, // 总税额
  totalAmountWithTax: 0, // 价税合计
  purchaserInfo: '', // 购买方信息
  sellerInfo: '', // 销售方信息
  remarks: '', // 备注信息
  issuer: '', // 开票人
  filePath: '', // 发票文件路径
  details: [createEmptyDetail()] // 发票明细
});

// 上传文件列表
const fileList = ref<UploadFile[]>([]);

// 加载状态
const loading = ref(false);

// 预览相关状态
const previewVisible = ref(false);
const previewUrl = ref('');
const isImageFile = ref(false);

// 添加上传状态和进度
const uploadLoading = ref(false);
const uploadProgress = ref(0);
const uploadStatus = ref('');
const uploadError = ref('');

// 表单验证规则
const rules = {
  invoiceNumber: [
    {required: true, message: '请输入发票号码', trigger: 'blur'}
  ],
  category: [
    {required: true, message: '请选择发票类别', trigger: 'change'}
  ],
  issueDate: [
    {required: true, message: '请选择开票日期', trigger: 'change'}
  ],
  purchaserInfo: [
    {required: true, message: '请输入购买方信息', trigger: 'blur'}
  ],
  sellerInfo: [
    {required: true, message: '请输入供应商信息', trigger: 'blur'}
  ]
};

// 获取发票详情
const fetchInvoiceDetail = async (id: string) => {
  try {
    loading.value = true;

    // 使用API模块获取发票详情
    const response = await getInvoiceById(id);

    // 检查API响应
    if (!response || !response.success) {
      throw new Error(response?.message || '获取发票数据失败');
    }

    // 获取真实的发票数据
    const invoiceData = response.data;

    if (!invoiceData) {
      throw new Error('获取发票详情失败：返回数据为空');
    }

    // 清空表单数据，防止数据混合
    Object.keys(invoiceForm).forEach(key => {
      if (key !== 'details') {
        invoiceForm[key] = '';
      }
    });

    // 逐个设置表单数据，避免直接Object.assign可能导致的引用问题
    invoiceForm.id = invoiceData.id || '';
    invoiceForm.invoiceNumber = invoiceData.invoiceNumber || '';
    invoiceForm.category = invoiceData.category || '';
    invoiceForm.issueDate = invoiceData.issueDate || '';
    invoiceForm.issuer = invoiceData.issuer || '';
    invoiceForm.remarks = invoiceData.remarks || '';

    // 处理purchaserInfo，可能是字符串也可能是对象
    if (invoiceData.purchaserInfo) {
      if (typeof invoiceData.purchaserInfo === 'string') {
        invoiceForm.purchaserInfo = invoiceData.purchaserInfo;
      } else {
        // 如果是对象，转为JSON字符串
        invoiceForm.purchaserInfo = JSON.stringify(invoiceData.purchaserInfo);
      }
    }

    // 处理sellerInfo，可能是字符串也可能是对象
    if (invoiceData.sellerInfo) {
      if (typeof invoiceData.sellerInfo === 'string') {
        invoiceForm.sellerInfo = invoiceData.sellerInfo;
      } else {
        // 如果是对象，转为JSON字符串
        invoiceForm.sellerInfo = JSON.stringify(invoiceData.sellerInfo);
      }
    }

    // 处理details数组，确保每个detail都包含必要的字段
    if (invoiceData.details && Array.isArray(invoiceData.details) && invoiceData.details.length > 0) {
      // 使用深拷贝避免引用问题
      invoiceForm.details = invoiceData.details.map(detail => {
        // 处理规格型号字段 - 优先使用specificationModel，如果不存在则尝试使用specification
        const specModel = detail.specificationModel || detail.specification || '';

        return {
          id: detail.id || undefined,
          itemName: detail.itemName || '',
          specificationModel: specModel,
          unit: detail.unit || '',
          quantity: detail.quantity ? parseFloat(String(detail.quantity)) : 1,
          unitPrice: detail.unitPrice ? parseFloat(String(detail.unitPrice)) :
              (detail.price ? parseFloat(String(detail.price)) : 0),
          taxRate: detail.taxRate ? parseFloat(String(detail.taxRate)) : 13,
          amount: typeof detail.amount === 'number' ? detail.amount.toFixed(2) : (detail.amount ? String(detail.amount) : '0.00'),
          taxAmount: typeof detail.taxAmount === 'number' ? detail.taxAmount.toFixed(2) : (detail.taxAmount ? String(detail.taxAmount) : '0.00'),
          totalAmount: detail.amount ? parseFloat(String(detail.amount)) : 0,
          specification: detail.specificationModel || detail.specification || ''
        };
      });

      // 重新计算总金额
      calculateTotals();

      ElMessage.success('获取发票详情成功');
    } else {
      // 如果没有明细，创建一个空明细
      invoiceForm.details = [createEmptyDetail()];
    }

    // 设置文件路径和文件列表
    invoiceForm.filePath = invoiceData.filePath || '';

    // 处理文件展示
    if (invoiceForm.filePath) {
      // 获取文件名
      const fileName = invoiceForm.filePath.split('/').pop() || '发票附件';

      // 获取完整文件URL
      const fileUrl = getFileUrl(invoiceForm.filePath);

      // 设置文件列表，用于展示
      fileList.value = [{
        name: fileName,
        url: fileUrl
      }];
    } else {
      // 清空文件列表
      fileList.value = [];
    }

    // 重新计算总金额
    calculateTotals();

    ElMessage.success('获取发票详情成功');
  } catch (error: any) {
    console.error('获取发票详情失败:', error);
    ElMessage.error(`获取发票详情失败: ${error.message || '请稍后重试'}`);
    // 初始化一个空表单
    invoiceForm.details = [createEmptyDetail()];
  } finally {
    loading.value = false;
  }
};

// 添加明细项
const addDetail = () => {
  invoiceForm.details.push(createEmptyDetail());
};

// 移除明细项
const removeDetail = (index: number) => {
  invoiceForm.details.splice(index, 1);
  calculateTotals();
};

// 计算单行明细金额
const calculateItemAmount = (index: number) => {
  const detail = invoiceForm.details[index];
  try {
    // 确保数据类型是数值类型
    const quantity = parseFloat(detail.quantity.toString()) || 0;
    const unitPrice = parseFloat(detail.unitPrice.toString()) || 0;

    // 计算金额并格式化（不含税金额）
    const amount = (quantity * unitPrice).toFixed(2);
    detail.amount = amount;

    // 计算税额并格式化
    const taxRate = parseFloat(detail.taxRate.toString()) || 0;
    const taxAmount = (parseFloat(amount) * taxRate / 100).toFixed(2);
    detail.taxAmount = taxAmount;

    // 设置总金额同步为不含税金额
    detail.totalAmount = parseFloat(amount);
  } catch (error) {
    console.error(`计算明细项[${index}]金额时出错:`, error);
  }

  // 更新总金额
  calculateTotals();
};

// 计算总金额
const calculateTotals = () => {
  let totalAmount = 0;
  let totalTax = 0;

  invoiceForm.details.forEach(detail => {
    totalAmount += parseFloat(detail.amount) || 0;
    totalTax += parseFloat(detail.taxAmount) || 0;
  });

  invoiceForm.totalAmount = totalAmount;
  invoiceForm.totalTax = totalTax;
  invoiceForm.totalAmountWithTax = totalAmount + totalTax;
};

// 合计金额
const totalAmount = computed(() => {
  return invoiceForm.totalAmount || 0;
});

// 合计税额
const totalTax = computed(() => {
  return invoiceForm.totalTax || 0;
});

// 价税合计
const totalAmountWithTax = computed(() => {
  return invoiceForm.totalAmountWithTax || 0;
});

// 提交表单
const submitForm = async () => {
  if (!invoiceFormRef.value) return;

  try {
    await invoiceFormRef.value.validate();

    // 保存前重新计算总金额
    calculateTotals();

    loading.value = true;

    // 构建保存参数，正确映射字段
    const saveData: Invoice = {
      ...invoiceForm,
      totalAmount: parseFloat(totalAmount.value.toString()) || 0,
      totalTax: parseFloat(totalTax.value.toString()) || 0,
      totalAmountWithTax: parseFloat(totalAmountWithTax.value.toString()) || 0,
      details: invoiceForm.details.map(detail => {
        // 确保所有数值字段都正确转换为数值类型
        const invoiceDetail: InvoiceDetail = {
          itemName: detail.itemName || '',
          unit: detail.unit || '',
          quantity: Number(detail.quantity) || 0,
          taxRate: Number(detail.taxRate) || 0,
          amount: Number(detail.amount) || 0,
          taxAmount: Number(detail.taxAmount) || 0,
          totalAmount: Number(detail.amount) || 0,
          unitPrice: Number(detail.unitPrice) || 0,
          specificationModel: detail.specificationModel || '',
          specification: detail.specificationModel || detail.specification || ''
        };

        // 如果是编辑模式且明细已有ID，则保留ID
        if (detail.id) {
          invoiceDetail.id = detail.id;
        }

        // 新增发票时invoiceId会由后端生成并设置
        if (isEdit.value && invoiceForm.id) {
          invoiceDetail.invoiceId = invoiceForm.id;
        }

        // 移除可能存在的旧ID，避免创建新发票时错误
        if (!isEdit.value && invoiceDetail.id) {
          delete invoiceDetail.id;
        }

        return invoiceDetail;
      })
    };

    // 判断是新增还是编辑
    let response;
    if (isEdit.value) {
      // 使用updateInvoice方法更新发票
      response = await updateInvoice(saveData.id!, saveData);
    } else {
      // 使用createInvoice方法创建发票
      response = await createInvoice(saveData);
    }

    // 检查API响应结果
    if (!response || !response.success) {
      throw new Error(response?.message || (isEdit.value ? '更新失败' : '添加失败'));
    }

    // 获取保存后的发票ID
    const savedInvoiceId = response.data?.id || invoiceForm.id;

    // 如果有临时文件，需要上传文件
    if (tempFile.value && savedInvoiceId) {
      try {
        // 显示上传进度条
        uploadProgress.value = 10;
        uploadLoading.value = true;

        // 上传文件到后端，直接指定invoiceId，后端会自动更新发票的文件路径
        const fileResponse = await uploadInvoiceFile(tempFile.value, savedInvoiceId);

        uploadProgress.value = 100;

        if (fileResponse && fileResponse.success) {
          uploadStatus.value = 'success';

          // 清除临时文件
          cleanupTempResources();

          // 刷新发票数据
          await fetchInvoiceDetail(savedInvoiceId);
        } else {
          throw new Error(fileResponse?.message || '文件上传失败');
        }
      } catch (error: any) {
        console.error('文件上传失败:', error);
        ElMessage.warning(`发票保存成功，但文件上传失败: ${error.message || ''}`);
      } finally {
        uploadLoading.value = false;
      }
    }

    ElMessage.success(isEdit.value ? '更新成功' : '添加成功');

    // 返回发票列表页面
    router.push('/dashboard/invoice-list');
  } catch (error: any) {
    console.error(isEdit.value ? '更新发票失败:' : '添加发票失败:', error);
    ElMessage.error(`${isEdit.value ? '更新' : '添加'}失败: ${error.message || '请稍后重试'}`);
  } finally {
    loading.value = false;
  }
};

// 处理文件变更
const handleFileChange = (file) => {
  // 存储文件到组件状态
  tempFile.value = file.raw;
  return false; // 阻止默认上传行为
};

// 处理文件移除
const handleFileRemove = () => {
  // 清除临时文件
  cleanupTempResources();
  fileList.value = [];
};

// 文件上传失败处理
const handleUploadError = (error: UploadError) => {
  uploadStatus.value = 'exception';
  uploadProgress.value = 0;
  uploadLoading.value = false;

  // 提取错误信息
  const errorMsg = error?.message || error?.response?.data?.message || '未知错误';
  uploadError.value = errorMsg;

  console.error('文件上传失败:', errorMsg);

  // 显示带有重试按钮的错误消息
  ElMessageBox.confirm(
      `文件上传失败: ${errorMsg}，是否重试？`,
      '上传错误',
      {
        confirmButtonText: '重试',
        cancelButtonText: '取消',
        type: 'error'
      }
  )
      .then(() => {
        // 用户点击重试
        if (tempFile.value) {
          const options = {
            file: tempFile.value,
            onSuccess: () => {
              ElMessage.success('重新上传成功');
            },
            onError: handleUploadError
          };
          customUploadRequest(options);
        }
      })
      .catch(() => {
        // 用户取消重试
        ElMessage.info('已取消重新上传');
      });
};

// 更新自定义上传请求，添加进度监控
const customUploadRequest = async (options: any) => {
  try {
    uploadLoading.value = true;
    uploadProgress.value = 0;
    uploadStatus.value = '';
    uploadError.value = '';

    const file = options.file;

    // 判断是否为图片文件
    const isImage = file.type.startsWith('image/');
    isImageFile.value = isImage;

    // 如果已经有发票ID，正常上传到服务器
    if (invoiceForm.id) {
      uploadProgress.value = 20; // 显示开始上传

      try {
        // 上传文件到后端，直接指定invoiceId，后端会自动更新发票的文件路径
        const response = await uploadInvoiceFile(file, invoiceForm.id);

        uploadProgress.value = 100;

        // 检查响应结果
        if (!response || !response.success) {
          throw new Error(response?.message || '文件上传失败');
        }

        uploadStatus.value = 'success';

        // 刷新发票数据
        await fetchInvoiceDetail(invoiceForm.id);

        // 更新文件列表
        fileList.value = [{
          name: file.name || '发票附件',
          url: response.data
        }];

        ElMessage.success('文件上传成功');

        // 处理上传结果
        if (options.onSuccess) {
          options.onSuccess(response);
        }
      } catch (error: any) {
        uploadStatus.value = 'exception';
        if (options.onError) {
          options.onError(error);
        }
        throw error;
      }
    } else {
      // 临时保存文件供表单提交时使用
      tempFile.value = file;

      // 创建一个临时的文件URL
      let tempFileURL = URL.createObjectURL(file);
      tempFileUrl.value = tempFileURL;

      // 更新文件列表显示
      fileList.value = [{
        name: file.name,
        url: tempFileURL
      }];

      // 提示用户文件已预览，提交表单时会上传
      ElMessage.success('文件已准备，保存表单时将自动上传');

      // 模拟上传成功
      uploadProgress.value = 100;
      uploadStatus.value = 'success';

      // 调用成功回调
      if (options.onSuccess) {
        options.onSuccess({code: 200, success: true, message: '文件已准备', data: tempFileURL});
      }
    }
  } catch (error: any) {
    console.error('文件上传错误:', error);
    if (options.onError) {
      options.onError(error);
    }
    handleUploadError(error);
  } finally {
    uploadLoading.value = false;
  }
};

// 文件预览
const handlePreview = (file) => {
  const url = file.url || '';
  if (!url) {
    ElMessage.warning('无法预览文件');
    return;
  }

  // 检查是否为图片文件
  const isImage = checkIsImageFile(url);

  if (isImage) {
    // 图片使用内部对话框预览
    previewUrl.value = url;
    previewVisible.value = true;
  } else {
    // 非图片文件使用浏览器打开
    window.open(url, '_blank');
  }
};

// 检查是否为图片文件
const checkIsImageFile = (url: string): boolean => {
  const lower = url.toLowerCase();
  return lower.endsWith('.jpg') || lower.endsWith('.jpeg') ||
      lower.endsWith('.png') || lower.endsWith('.gif') ||
      lower.endsWith('.bmp') || lower.includes('image/');
};

// 上传前钩子
const handleBeforeUpload = (file: File) => {
  // 判断文件类型
  const isImage = file.type.startsWith('image/');
  isImageFile.value = isImage;

  // 文件类型检查
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
  const isAllowed = allowedTypes.includes(file.type);

  if (!isAllowed) {
    ElMessage.error('不支持的文件格式，仅支持JPG、PNG、GIF和PDF文件');
    return false;
  }

  // 文件大小检查（10MB限制）
  const maxSize = 10 * 1024 * 1024;
  if (file.size > maxSize) {
    ElMessage.error('文件大小超过限制，最大支持10MB');
    return false;
  }

  // 将创建的blob URL存储起来，以便从内存中释放
  if (isImage && !invoiceForm.id) {
    const blobUrl = URL.createObjectURL(file);
    tempFileUrl.value = blobUrl;
  }

  return true; // 允许上传
};

// 移除文件
const handleRemove = (file, fileList) => {
  // 清除临时文件
  handleFileRemove();
};

// 文件移除前确认
const beforeRemove = () => {
  return ElMessageBox.confirm('确定移除此文件？', '提示', {
    type: 'warning'
  });
};

// 返回发票列表
const goBack = () => {
  router.push('/dashboard/invoice-list');
};

// 格式化金额
const formatAmount = (amount: number) => {
  if (amount === undefined || amount === null) return '0.00';
  return amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 下载文件
const downloadFile = (file) => {
  const url = file.url || '';
  if (!url) {
    ElMessage.warning('没有可下载的文件');
    return;
  }

  // 创建一个临时的a标签用于下载
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', file.name || '发票附件');
  document.body.appendChild(link);
  link.click();

  // 删除临时创建的a标签
  document.body.removeChild(link);

  ElMessage.success('开始下载文件');
};

// 组件挂载时初始化
onMounted(() => {
  if (isEdit.value && route.params.id) {
    fetchInvoiceDetail(route.params.id as string);
  }
});
</script>

<style scoped>
.invoice-edit-container {
  padding: 20px;
}

.form-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-top: 20px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.detail-table {
  margin: 20px 0;
}

.el-input-number {
  width: 100%;
}

.amount-summary {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin: 16px 0;
  padding: 16px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.amount-item {
  display: flex;
  margin-bottom: 8px;
}

.amount-label {
  width: 80px;
  text-align: right;
  color: #606266;
}

.amount-value {
  width: 120px;
  text-align: right;
  font-weight: bold;
}

.total-price {
  color: #f56c6c;
  font-size: 16px;
}

/* 上传容器样式 */
.upload-container {
  margin-bottom: 20px;
}

/* 图片预览样式 */
.preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

/* 上传组件样式 */
.el-upload {
  display: flex;
  flex-wrap: wrap;
}

.el-upload--picture-card {
  width: 148px;
  height: 148px;
  margin-right: 8px;
  margin-bottom: 8px;
  line-height: 146px;
}

/* 文件类型上传按钮 */
.upload-demo .el-button {
  margin-right: 10px;
}

/* 上传文件列表中的图片卡片 */
.el-upload-list--picture-card {
  display: flex;
  flex-wrap: wrap;
}

.el-upload-list--picture-card .el-upload-list__item {
  overflow: hidden;
  background-color: #fff;
  border: 1px solid #c0ccda;
  border-radius: 6px;
  box-sizing: border-box;
  width: 148px;
  height: 148px;
  margin: 0 8px 8px 0;
  display: inline-block;
  position: relative;
}

/* 帮助提示信息 */
.el-upload__tip {
  margin-top: 10px;
  color: #606266;
  font-size: 13px;
}
</style>